package com.aidong.pay.action;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.apache.struts2.convention.annotation.Result;
import org.apache.struts2.json.annotations.JSON;
import org.springframework.beans.factory.annotation.Autowired;

import com.aidong.activity.action.MstCampaignAction;
import com.aidong.coupons.biz.MstCouponsBiz;
import com.aidong.jobs.async.SmsTask;
import com.aidong.login.biz.MemberLocationReportBiz;
import com.aidong.pay.biz.MsmAppointmentToRemindBiz;
import com.aidong.pay.biz.OrderManagementBiz;
import com.aidong.pay.biz.OrdergeneratedBiz;
import com.aidong.pay.config.util.ClenderUtil;
import com.aidong.pay.entity.TrnCampaignSignOrder;
import com.aidong.util.CalendarUtil;
import com.opensymphony.xwork2.ModelDriven;

@ParentPackage("json")
@Namespace("/")
public class AlipayProcessAction implements ModelDriven<TrnCampaignSignOrder>{

	private TrnCampaignSignOrder trnCampaignSignOrder;
	@Autowired
	private OrdergeneratedBiz ordergeneratedBiz;
	@Autowired
	private MsmAppointmentToRemindBiz appointmentToRemindBiz;
	@Autowired
	private OrderManagementBiz orderManagementBiz;
	@Autowired
	private MstCouponsBiz mstCouponsBiz;
	@Autowired
	private MemberLocationReportBiz memberLocationReportBiz;
	@Autowired
	SmsTask smsTask;

	private Map<String, Object> map;

	@JSON
	public Map<String, Object> getMap() {
		return map;
	}
	@Override
	public TrnCampaignSignOrder getModel() {
		if (trnCampaignSignOrder == null) {
			trnCampaignSignOrder = new TrnCampaignSignOrder();
		}
		return trnCampaignSignOrder;
	}

	/**
	 * 支付同步通知
	 * 
	 * @return
	 */
	@Action(value = "editorderstatus", results = { @Result(name = "succ", type = "json", params = { "root", "map" }) })
	public String editOrderStatus() {
		int orderId = trnCampaignSignOrder.getOrderId();
		String number = trnCampaignSignOrder.getNumber();
		map = new HashMap<String, Object>();
		System.out.println("===============支付同步通知：订单号" + orderId + "；码：" + number);
		if (orderId > 0) {
			try {
				// 主动查询回调状态
				Map<String, Object> paraMap = new HashMap<String, Object>();
				paraMap.put("ticketNum", number);
				paraMap.put("orderId", orderId);
				Map<String, Object> statuMap = orderManagementBiz.getOrderBackStatus(paraMap);
				System.out.println("===============支付同步通知：订单信息" + statuMap);
				int orderType = Integer.parseInt(statuMap.get("orderType").toString()); // 订单类型
				int idongId = Integer.valueOf(statuMap.get("idongId").toString());
				paraMap.put("idongId", idongId);
				int orderStatus = Integer.parseInt(statuMap.get("status").toString()); // 订单状态ID
				int orderProcess = Integer.parseInt(statuMap.get("processId").toString()); // 订单流程ID
				double actually = Double.parseDouble(statuMap.get("actually").toString());
				int payType = Integer.parseInt(statuMap.get("payType").toString()); // 支付方式

				String validTime = ""; // 有效时间
				String tickNo = ""; // 电子券号

				Map<String, Object> memberMap = ordergeneratedBiz.getPayMemberPhone(orderId);
				if (actually <= 0) {
					tickNo = ClenderUtil.electronicTicketNo(memberMap.get("phoneNo").toString()); // 电子券号
					Map<String, Object> orderMap = new HashMap<String, Object>();
					orderMap.put("payTime", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
					orderMap.put("tickNo", tickNo);
					orderMap.put("orderId", orderId);
					orderMap.put("tradeNo", 1);
					orderMap.put("status", 1);
					orderMap.put("processId", 2);
					orderManagementBiz.editOrderPayInfo(orderMap);

					// add 2016-01-14 更新兑换券或者代金券表 码的使用状态及订单ID
					if (payType == 4) { // 兑换券
						orderManagementBiz.editexchangeTicketsInfoOrderIdUse(paraMap);// 将券的使用人、使用订单填进去
					} else if (payType == 3) { // 代金券
						orderManagementBiz.editCouponsInfoOrderIdUse(paraMap);
					} else if (payType == 6) {// 折扣券
						orderManagementBiz.editDiscountInfoOrderIdUse(orderMap);
					}
					Map<String, Object> validMap = ordergeneratedBiz.getCampaginValidTime(orderId);
					if (validMap != null) {
						validTime = validMap.get("startTime").toString();
					}

					if (orderType == 1 || orderType == 6) { // 活动/赛事
						Map<String, Object> activityTypeMap = ordergeneratedBiz.getActivityType(orderId);
						int moviceFlag = Integer.valueOf(activityTypeMap.get("movieFlg").toString());
						Map<String, Object> mstMap = appointmentToRemindBiz.addCampaginRemind(orderId);
						String cellNumber = mstMap.get("phoneNo").toString(); // 电话号码
						String title = mstMap.get("title").toString(); // 活动标题
						String subscribeId = mstMap.get("subscribeId").toString(); // 预约ID
						String date = mstMap.get("startTime").toString(); // 活动开始时间
						String address = mstMap.get("place").toString(); // 活动地点

						if (moviceFlag == 0) {
							String voucherNo = mstMap.get("tickNo").toString(); // 核销电子券号
							// 手机号码后四位
							String latFourPhone = voucherNo.substring(voucherNo.length() - 4, voucherNo.length());
							// 电子券号前八位
							String topEight = voucherNo.substring(0, 8);
							// 短信提醒
							smsTask.activityRemind(cellNumber, title, subscribeId, date, address, topEight,
									latFourPhone);
						} else if (moviceFlag == 3) { // 票务
							// 根据取货方式确定要发送的短信
							int subscribeId1 = Integer.parseInt(statuMap.get("subscribeId").toString()); // 预约号
							// 根据预约号获取取货方式
							Map<String, Object> paraMap1 = new HashMap<String, Object>();
							paraMap1.put("subscribeId", subscribeId1);
							Map<String, Object> pickUpMap = orderManagementBiz.getCampaignPickUpWay(paraMap1);

							int pickUpWay = Integer.parseInt(pickUpMap.get("pickUpWay").toString());
							if (pickUpWay == 1) {// 选门店

							} else if (pickUpWay == 3) {// 虚拟码
						
							}
						}
					} else if (orderType == 2) { // 课程
						Map<String, Object> courseMap = appointmentToRemindBiz.addCourseRemind(orderId);
						String cellNumber = courseMap.get("phoneNo").toString(); // 电话号码
						String subscribeCourseId = courseMap.get("subscribeId").toString(); // 预约ID
						String courseName = courseMap.get("coureName").toString(); // 课程名
						String date = courseMap.get("subscribeDate").toString(); // 上课日期
						String time = courseMap.get("startTime").toString(); // 上课时间
						String dateTime = date + " " + time; // 上课开始时间
						String storeName = courseMap.get("storeName").toString(); // 场馆名
						String voucherNo = courseMap.get("tickNo").toString(); // 券号
						/*
						 * SMSUtil.pool.execute(new Runnable() { public void
						 * run() {
						 */
						try {
							// 手机号码后四位
							String latFourPhone = voucherNo.substring(voucherNo.length() - 4, voucherNo.length());
							// 电子券号前八位
							String topEight = voucherNo.substring(0, 8);
							// 短信提醒
							smsTask.courseAppointment(cellNumber, subscribeCourseId, courseName, dateTime, storeName,
									topEight, latFourPhone);
						} catch (Exception e) {
							e.printStackTrace();
						}
						/*
						 * } });
						 */
					} else if (orderType == 3 || orderType == 4 || orderType == 5) { // 健康餐饮、营养品、装备
						Map<String, Object> foodMap = appointmentToRemindBiz.addFoodBuyRemind(orderId);
						String phoneNo = foodMap.get("phoneNo").toString(); // 电话号码
						String quantity = foodMap.get("quantity").toString(); // 数量
						String foodName = foodMap.get("foodName").toString(); // 餐名
						String buyDate = foodMap.get("buyDate").toString(); // 预订日期
						String pickUpForm = foodMap.get("pickUpForm").toString(); // 取餐开始日期
						String pickUpTo = foodMap.get("pickUpTo").toString(); // 取餐截止如期
						String pickDate = buyDate + " " + pickUpForm + "-" + pickUpTo;
						String storeName = foodMap.get("storeName").toString(); // 门店
						String voucherNo = foodMap.get("tickNo").toString(); // 电子券号
						String pickUpWay = foodMap.get("pickUpWay").toString(); // 取货方式
						/*
						 * SMSUtil.pool.execute(new Runnable() { public void
						 * run() {
						 */
						try {
							// 手机号码后四位
							String latFourPhone = voucherNo.substring(voucherNo.length() - 4, voucherNo.length());
							// 电子券号前八位
							String topEight = voucherNo.substring(0, 8);
							// 短信提醒
							if ("2".equals(pickUpWay)) {
								smsTask.foodAppointmentT(phoneNo, quantity, foodName);
							} else {
								smsTask.foodAppointment(phoneNo, quantity, foodName, pickDate, storeName, topEight,
										latFourPhone);
							}
						} catch (Exception e) {
							e.printStackTrace();
						}
						/*
						 * } });
						 */
					}

					Map<String, Object> resultMap = new HashMap<String, Object>();
					resultMap.put("message", "");
					if(orderType==2 && "3".equals(statuMap.get("brandId"))){
						Date date = new Date();
						SimpleDateFormat sm = new SimpleDateFormat("yyyy-MM-dd");
						Date time=sm.parse("2017-03-01");
						if(date.getTime()>time.getTime()){
							resultMap.put("message", "  三月一号起，课程预约迁至微信公众号，请前往预约  三月一号起，课程预约迁至微信公众号，请前往预约 ");
						}
						
					}
					resultMap.put("validTime", validTime);

					resultMap.put("name", memberMap.get("name").toString());
					resultMap.put("phoneNo", memberMap.get("phoneNo").toString());

					// 如果支付成功，查询用户信息表中任务标签task1是否已点亮，点亮则不作处理，未点亮则进行点亮操作
					Map<String, Object> userInfo = memberLocationReportBiz.getInfoByIdongId(idongId);
					if (userInfo != null) {
						// 查询出活动预约订单的当月数量大于2
						int count = memberLocationReportBiz.getCountCampaignSignOrder(idongId);
						if (userInfo.containsKey("task2") && "0".equals(userInfo.get("task2")) && count >= 2) {
							// 更新任务标签2为已点亮
							Map<String, Object> map = new HashMap<String, Object>();
							map.put("idongId", idongId);
							map.put("task1", "");
							map.put("task2", "1");
							map.put("task3", "");
							memberLocationReportBiz.updateTaskByIdongId(map);
						}
					}
					map.put("code", 1);
					map.put("result", resultMap);
					return "succ";
				}
				System.out.println(orderStatus + "========订单状态==========" + orderProcess);
				if (orderStatus == 1 && orderProcess == 2) { // 支付成功
					// 如果支付成功，查询用户信息表中任务标签task1是否已点亮，点亮则不作处理，未点亮则进行点亮操作
					Map<String, Object> userInfo = memberLocationReportBiz.getInfoByIdongId(idongId);
					if (userInfo != null) {
						if (userInfo.containsKey("task1") && "0".equals(userInfo.get("task1"))) {
							// 更新任务标签1为已点亮
							Map<String, Object> map = new HashMap<String, Object>();
							map.put("idongId", idongId);
							map.put("task1", "1");
							map.put("task2", "");
							map.put("task3", "");
							memberLocationReportBiz.updateTaskByIdongId(map);
						}
						// 查询出活动预约订单的当月数量大于2
						int count = memberLocationReportBiz.getCountCampaignSignOrder(idongId);
						if (userInfo.containsKey("task2") && "0".equals(userInfo.get("task2")) && count >= 2) {
							// 更新任务标签2为已点亮
							Map<String, Object> map = new HashMap<String, Object>();
							map.put("idongId", idongId);
							map.put("task1", "");
							map.put("task2", "1");
							map.put("task3", "");
							memberLocationReportBiz.updateTaskByIdongId(map);
						}
					}
					System.out.println("---------===========" + orderType);
					if (orderType == 1 || orderType == 6) { // 活动或票务
						Map<String, Object> validMap = ordergeneratedBiz.getCampaginValidTime(orderId);
						validTime = validMap.get("startTime").toString();

						Map<String, Object> mstMap = appointmentToRemindBiz.addCampaginRemind(orderId);
						tickNo = mstMap.get("tickNo").toString(); // 券号
					} else if (orderType == 2) { // 课程
						Map<String, Object> validMap = ordergeneratedBiz.getCourseValidTime(orderId);
						validTime = validMap.get("subscribeDate").toString(); // 上课日期

						Map<String, Object> courseMap = appointmentToRemindBiz.addCourseRemind(orderId);
						tickNo = courseMap.get("tickNo").toString(); // 券号
					} else if (orderType == 3 || orderType == 4 || orderType == 5) { // 健康餐饮
						Map<String, Object> validMap = ordergeneratedBiz.getPickValidTime(orderId);
						validTime = validMap.get("buyDate") + " " + validMap.get("formDate") + "-"
								+ validMap.get("toDate");

						Map<String, Object> foodMap = appointmentToRemindBiz.addFoodBuyRemind(orderId);
						tickNo = foodMap.get("tickNo").toString(); // 电子券号
					}

					Map<String, Object> resultMap = new HashMap<String, Object>();
					
					resultMap.put("tickNo", tickNo);
					resultMap.put("validTime", validTime);

					resultMap.put("name", memberMap.get("name").toString());
					resultMap.put("phoneNo", memberMap.get("phoneNo").toString());

					map.put("code", 1);
					map.put("result", resultMap);
					return "succ";
				} else {
					// 将券的状态改回到未使用1：支付宝 2：微信 3：代金券 4：兑换券 5：支付宝+代金券 6：微信+代金券
					// 7:支付宝+折扣券 8：微信+折扣券
					if (payType == 3 || payType == 5 || payType == 6) { // 代金券
						orderManagementBiz.setCouponsTicketsUnuse(paraMap);
					}
					if (payType == 7 || payType == 8) { // 折扣券
						orderManagementBiz.setDiscountTicketsUnuse(paraMap);
					}
					map.put("code", 0);
					map.put("msg", "支付失败");
					return "succ";
				}
			} catch (Exception e) {
				e.printStackTrace();
				map.put("code", 0);
				map.put("msg", "系统异常");
				return "succ";
			}
		} else {
			map.put("code", 0);
			map.put("msg", "参数缺失");
			return "succ";
		}
	}

	/**
	 * 去支付 得到支付剩余时间
	 * 
	 * @return
	 */
	@Action(value = "getgotopaytime", results = { @Result(name = "succ", type = "json", params = { "root", "map" }) })
	public String getGoToPayTime() {
		int orderId = trnCampaignSignOrder.getOrderId();
		map = new HashMap<String, Object>();
		if (orderId > 0) {
			try {
				Map<String, Object> timeMap = ordergeneratedBiz.getGoToPayTime(orderId);

				String campaignId = timeMap.get("campaignId") + ""; // 下单时间

				String orderType = timeMap.get("orderType") + ""; // 下单类型

				int createdTime = Integer.parseInt(timeMap.get("surplusTime").toString()); // 剩余时间
				if ("null".equals(campaignId)) {
					campaignId = "";
				}

				int timeRemaining = CalendarUtil.payOverTimeCancle(createdTime, orderType);
				if (timeRemaining == 0) {
					map.put("code", 0);
					map.put("msg", "支付超时");
					return "succ";
				} else {
					Map<String, Object> result = new HashMap<String, Object>();
					result.put("surplusTime", timeRemaining + "");
					result.put("campaignId", campaignId);

					Map<String, Object> payInfo = new HashMap<String, Object>();
					String strInfo = ordergeneratedBiz.getGoToPayInfo(orderId);
					List<Map<String, Object>> pays = new MstCampaignAction().getPayInfo(strInfo);
					payInfo.put("zhifubao", pays.get(0).get("zhifubao"));
					payInfo.put("weixin", pays.get(1).get("weixin"));
					payInfo.put("voucher", pays.get(2).get("voucher"));
					payInfo.put("exchange", pays.get(3).get("exchange"));
					payInfo.put("membership", pays.get(4).get("membership"));
					payInfo.put("discount", pays.get(5).get("discount"));
					result.put("payInfo", payInfo);

					map.put("code", 1);
					map.put("result", result);
					return "succ";
				}
			} catch (Exception e) {
				e.printStackTrace();
				map.put("code", 0);
				map.put("msg", "系统异常");
				return "succ";
			}
		} else {
			map.put("code", 0);
			map.put("msg", "参数缺失");
			return "succ";
		}
	}

	/**
	 * 记录订单金额支付信息
	 * 
	 * @return
	 */
	@Action(value = "addordersumcase", results = { @Result(name = "succ", type = "json", params = { "root", "map" }) })
	public String addOrderSumCase() {
		map = new HashMap<String, Object>();
		int payType = trnCampaignSignOrder.getPayType(); // 支付方式
		String number = trnCampaignSignOrder.getNumber(); // 券号
		int orderId = trnCampaignSignOrder.getOrderId(); // 订单ID
		int idongId = trnCampaignSignOrder.getIdongId();
		if (payType > 0 && orderId > 0 && !"".equals(number) && null != number) {
			try {
				Map<String, Object> paraMap1 = new HashMap<String, Object>();
				paraMap1.put("orderId", orderId);
				paraMap1.put("couponsNum", number);
				paraMap1.put("exchangeTicketNum", number);
				paraMap1.put("idongId", idongId);// 此处不记录使用人 都是0元的-为什么不记录
													// 能不能记录-2016-3-21改为记录爱动号
				// 区分是代金券还是兑换券1：支付宝 2：微信 3：代金券 4：兑换券 5：支付宝+代金券 6：微信+代金券
				if (payType == 3) {
					// 将订单ID填入到代金券表，并设置为已使用
					orderManagementBiz.editCouponsInfoOrderId(paraMap1);
					if ((Integer) paraMap1.get("updateResult") == 0) {
						map.put("code", 0);
						map.put("msg", "代金券无效");
						return "succ";
					}
				} else if (payType == 4) {
					orderManagementBiz.editExchangeTicketsInfo(paraMap1);
					if ((Integer) paraMap1.get("updateResult") == 0) {
						map.put("code", 0);
						map.put("msg", "兑换券无效");
						return "succ";
					}
				}
				if (payType == 3) {
					Map<String, Object> paraMap = new HashMap<String, Object>();
					paraMap.put("couponsNum", number.toUpperCase());
					Map<String, Object> resultMap = new HashMap<String, Object>();
					resultMap = mstCouponsBiz.getCouponsInfo(paraMap);
					double priceCoupons = Double.parseDouble(resultMap.get("couponsPrice").toString());
					double privilege = 0.00, actually = 0.00;

					privilege = priceCoupons;// 优惠金额 存储券的价格
					paraMap.put("privilege", privilege);
					paraMap.put("actually", actually);
					paraMap.put("freight", 0.00);
					paraMap.put("goodsActually", 0.00);
					paraMap.put("payType", payType);
					paraMap.put("orderId", orderId);
					ordergeneratedBiz.editorderPayTypeCoupons(paraMap);

					map.put("code", 1);
					map.put("result", true);
					return "succ";
				} else if (payType == 4) {// 兑换券
					Map<String, Object> paraMap = new HashMap<String, Object>();
					paraMap.put("couponsNum", number.toUpperCase());
					double privilege = 0.00, actually = 0.00;
					paraMap.put("privilege", privilege);
					paraMap.put("actually", actually);
					paraMap.put("freight", 0.00);
					paraMap.put("goodsActually", 0.00);
					paraMap.put("payType", payType);
					paraMap.put("orderId", orderId);
					ordergeneratedBiz.editorderPayTypeExchanges(paraMap);// .editorderPayTypeCoupons(paraMap);

					map.put("code", 1);
					map.put("result", true);
					return "succ";
				} else {
					map.put("code", 0);
					map.put("msg", "调用无效");
					return "succ";
				}

			} catch (Exception e) {
				e.printStackTrace();
				map.put("code", 0);
				map.put("msg", "系统异常");
				return "succ";
			}
		} else {
			map.put("code", 0);
			map.put("msg", "参数缺失");
			return "succ";
		}
	}
}